<script setup lang="js">
import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted } from 'vue'
import anlyze from "../../apis/anlyze.js"

const chartRef = ref(null)
let myChart = null
let currentLevel = 'year'

// 动态计算 Y 轴配置（单位25）
const calcYAxis = (maxValue) => {
  const step = 25
  let max = Math.ceil(maxValue / step) * step
  if (max < step * 4) max = step * 4
  return {
    max,
    splitNumber: max / step
  }
}

// 中文月份映射到数字
const monthMap = {
  '一月': 1,
  '二月': 2,
  '三月': 3,
  '四月': 4,
  '五月': 5,
  '六月': 6,
  '七月': 7,
  '八月': 8,
  '九月': 9,
  '十月': 10,
  '十一月': 11,
  '十二月': 12
}

const extractMonthNumberFromChinese = (monthLabel) => {
  return monthMap[monthLabel] || NaN
}

// 基础配置
const baseOption = {
  title: {
    text: '志愿者注册数据',
    left: 'center',
    top: 30,
    textStyle: {
      color: '#333',
      fontSize: 18,
      fontWeight: 'bold'
    }
  },
  backgroundColor: 'transparent',
  textStyle: {
    fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    containLabel: true
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
      shadowStyle: {
        color: 'rgba(150, 150, 150, 0.1)'
      }
    },
    backgroundColor: 'rgba(255,255,255,0.95)',
    borderWidth: 0,
    padding: [8, 12],
    textStyle: {
      color: '#333',
      fontSize: 12
    },
    extraCssText: 'box-shadow: 0 2px 8px rgba(0,0,0,0.1);'
  },
  legend: {
    textStyle: {
      color: '#666'
    },
    itemHeight: 12,
    itemWidth: 12,
    itemGap: 16
  },
  xAxis: {
    axisLine: {
      lineStyle: {
        color: '#646161'
      }
    },
    axisLabel: {
      color: '#5b4f4f',
      rotate: 45,
      margin: 15,
      align: 'right',
      verticalAlign: 'middle',
      interval: 0,
      fontSize: 12
    }
  },
  yAxis: {
    axisLine: {
      show: false
    },
    axisTick: {
      show: false
    },
    splitLine: {
      lineStyle: {
        color: '#f0f0f0',
        type: 'dashed'
      }
    },
    axisLabel: {
      color: '#666'
    }
  }
}

onMounted(() => {
  myChart = echarts.init(chartRef.value)
  loadYearData()
  myChart.on('click', handleClick)

  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  if (myChart) {
    const width = chartRef.value.offsetWidth
    const option = myChart.getOption()

    // 响应式调整X轴标签
    if (width < 768) {
      option.xAxis[0].axisLabel.rotate = 30
      option.xAxis[0].axisLabel.fontSize = 10
      option.grid.bottom = '20%'
    } else {
      option.xAxis[0].axisLabel.rotate = 45
      option.xAxis[0].axisLabel.fontSize = 12
      option.grid.bottom = '15%'
    }

    myChart.setOption(option)
    myChart.resize()
  }
}

// ✅ 年视图（堆叠图：本月注册 + 累计注册）
const loadYearData = async () => {
  try {
    const res = await anlyze.getVolunteersCountByMonth()
    const parsed = JSON.parse(res)
    const xAxis = parsed.xAxis
    let seriesData = parsed.seriesData

    // 添加堆叠配置
    seriesData = seriesData.map((series, index) => ({
      name: index === 0 ? '本月注册' : '累计注册',
      type: 'bar',
      stack: '总量',
      barWidth: '60%',
      data: series.data,
      itemStyle: {
        color: index === 0
            ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#5B8FF9' },
              { offset: 1, color: '#3A6FD9' }
            ])
            : '#E8EDF3',
        borderRadius: [4, 4, 0, 0]
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        }
      }
    }))

    const yAxisCfg = calcYAxis(Math.max(...seriesData[1].data))
    currentLevel = 'year'

    myChart.setOption({
      ...baseOption,
      legend: {
        ...baseOption.legend,
        data: ['本月注册', '累计注册']
      },
      xAxis: {
        ...baseOption.xAxis,
        type: 'category',
        data: xAxis
      },
      yAxis: {
        ...baseOption.yAxis,
        type: 'value',
        max: yAxisCfg.max,
        splitNumber: yAxisCfg.splitNumber
      },
      series: seriesData,
      animationDurationUpdate: 300,
      animationEasing: 'elasticOut',
      animationDelayUpdate: function(idx) {
        return idx * 5;
      },
      graphic: []
    }, true)
  } catch (error) {
    console.error('加载年份数据失败:', error)
  }
}

// ✅ 月视图（只显示每日注册人数，不显示累计）
const loadMonthData = async (monthNumber) => {
  if (isNaN(monthNumber)) {
    console.warn('无效的月份参数:', monthNumber)
    return
  }
  try {
    const res = await anlyze.getVolunteersCountByWeek({ data: monthNumber })
    const parsed = JSON.parse(res)
    const xAxis = parsed.xAxis
    const seriesData = parsed.seriesData

    const yAxisCfg = calcYAxis(Math.max(...seriesData[0].data))
    currentLevel = 'month'

    myChart.setOption({
      ...baseOption,
      tooltip: {
        ...baseOption.tooltip,
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      legend: {
        ...baseOption.legend,
        data: [seriesData[0].name || '当日注册']
      },
      xAxis: {
        ...baseOption.xAxis,
        type: 'category',
        data: xAxis
      },
      yAxis: {
        ...baseOption.yAxis,
        type: 'value',
        max: yAxisCfg.max,
        splitNumber: yAxisCfg.splitNumber
      },
      series: [{
        ...seriesData[0],
        barWidth: '40%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#0b95d6' },
            { offset: 1, color: '#5B86E5' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        }
      }],
      animationDurationUpdate: 300,
      animationEasing: 'elasticOut',
      graphic: [{
        type: 'text',
        left: 20,
        top: 10,
        style: {
          text: '← 返回年度视图',
          fontSize: 14,
          fontWeight: 'bold',
          fill: '#5B8FF9',
          cursor: 'pointer'
        },
        onclick: loadYearData
      }]
    }, true)
  } catch (error) {
    console.error('加载月数据失败:', error)
  }
}

// 点击事件处理，年视图点击转月视图
const handleClick = (event) => {
  if (currentLevel === 'year' && event.name) {
    const monthNumber = extractMonthNumberFromChinese(event.name)
    if (!isNaN(monthNumber)) {
      loadMonthData(monthNumber)
    } else {
      console.warn('无法解析中文月份:', event.name)
    }
  }
}
</script>

<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart {
  width: 100%;
  height: 550px;
}

@media (max-width: 768px) {
  .chart-container {
    padding: 10px;
  }

  .chart {
    height: 400px;
  }
}
</style>